#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include "mytype.h"
#include "net.h"
#include <sys/wait.h>
#include <time.h>

void sig_chld(int signo)
{
	pid_t pid;
	int stat;
	while((pid=waitpid(-1,&stat,WNOHANG))>0)
		printf("child %d terminated\n",pid);
	return;
}

int open_server()
{
	int iRet,listenfd, connectfd ,lenth;
	pid_t pid;
	int flag=1,len=sizeof(int); 
	struct sockaddr_in servaddr,client;
	time_t count;
	struct tm *serv_time;
	char buffer[MAXLINE];
	bzero(&servaddr,sizeof(servaddr));
	bzero(&client,sizeof(client));
	if((listenfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
	{
		perror("socket creat error");
		return -1;
	}
	if((iRet = setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&flag,len)) < 0) 
	{ 
		perror("set socket opt error");
		return -1; 
	} 	
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(9999);
	if((iRet = bind(listenfd, (struct sockaddr *) &servaddr,sizeof(servaddr))) == -1)
	{
		perror("bind error");
		return -1;
	}
	if((iRet = listen(listenfd,10)) == -1)
	{
		perror("listen error");
		return -1;
	}
	signal(SIGCHLD,sig_chld);
	while(1)
	{
		lenth = sizeof(client);
		connectfd=accept(listenfd,(struct sockaddr *) &client, &lenth);
		pid = fork();
		if(pid < 0)
		{
			perror("fork error");
		}
		else if(pid == 0)
		{
			count = time(NULL);
			serv_time = localtime(&count);
			printf("%d/%d/%d/n",serv_time->tm_mon+1,serv_time->tm_mday,serv_time->tm_year+1900);  
			printf("%d:%d:%d/n",serv_time->tm_hour,serv_time->tm_min,serv_time->tm_sec); 
			printf("Creat child process,pid is %d\n",getpid());
			while(1)
			{
				while((iRet=read(connectfd,buffer,sizeof(buffer)) != 0))
				{
					printf("get from client(pid %d): %s\n",getpid(),buffer);
					write(connectfd,buffer,iRet);
                    if(strncmp(buffer,"exit",strlen("exit"))==0)
                    {
                        exit(0);
                    }
					bzero(buffer,0);
//					exit(0);
				}
//				exit(0);
			}
		}
		else
		{
			continue;
		}
		
//		waitpid(pid,&iRet,0);
//		printf("child process exit with %d\n",iRet);
#if 0
		while((iRet=read(connectfd,buffer,sizeof(buffer)) != 0))
		{
			printf("get from client: %s\n",buffer);
			write(connectfd,buffer,iRet);
			bzero(buffer,0);
		}

		continue;
#endif
	}
	return 0;	
}

int main()
{
	open_server();
	return 0;
}

